<?php

namespace App\Services\Draw\PoolGroupObject;


use App\Exceptions\BasicException;
use App\Repositories\GiftRepository;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;

/**
 * 扭蛋抽奖实体
 * @author wrh
 */
class PetIndependentPoolGroup extends IndependentPoolGroup
{

    public function getNewPoolGroup()
    {
        //group变更时更新数据 需要加锁
        $groupIds = explode(',', $this->group_ids);
        if (empty($groupIds)) {
            throw new BasicException(-1, "模板未配置");
        }

        $poolIndependent = $this->poolIndependentModel->one(['id' => $this->independent_id], true);
        $groupFlipIds        = array_flip($groupIds);
        if ($poolIndependent->group_id == 0) {
            $groupKey = 0;
        } else {
            $groupKey = $groupFlipIds[$poolIndependent->group_id] + 1 <= (count($groupIds) - 1) ? $groupFlipIds[$poolIndependent->group_id] + 1 : 0;
        }

        $this->group_id = $groupIds[$groupKey];
        return $this;
    }


    public function updatePoolDrawData(array $drawIOPut, int $poolIncrRound, int $drawCount)
    {
        $poolUpdateData = $this->updateNormalPoolDrawData($this, $drawIOPut, $poolIncrRound, $drawCount);

        $input  = $drawIOPut['input'];
        $output = $drawIOPut['output'];
        //独立池子投入产出更新
        $independentUpdateData['input']  = DB::raw('input +' . $input);
        $independentUpdateData['output'] = DB::raw('output +' . $output);
        if ($this->group_id != $this->current_group_id) {
            //切换组合的时候清空当前投入产出
            $independentUpdateData['group_id'] = $this->group_id;
            if ($this->current_group_id == 0) {
                $independentUpdateData['input_pre']  = DB::raw('input_pre +' . $input);
                $independentUpdateData['output_pre'] = DB::raw('output_pre +' . $output);
            } else {
                $independentUpdateData['input_pre']  = $input;
                $independentUpdateData['output_pre'] = $output;
            }
        } else {
            $independentUpdateData['input_pre']  = DB::raw('input_pre +' . $input);
            $independentUpdateData['output_pre'] = DB::raw('output_pre +' . $output);
        }

        $this->poolIndependentModel->updateData(["id" => $this->independent_id], $independentUpdateData);

        return $poolUpdateData;
    }

}